package com.example.administrator.himalaya.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.administrator.himalaya.R;
import com.example.administrator.himalaya.entity.recommendentity.DiscoveryListEntity;
import com.example.administrator.himalaya.entity.recommendentity.FocusList;
import com.example.administrator.himalaya.entity.recommendentity.IF03DataEntity;
import com.example.administrator.himalaya.entity.recommendentity.RecommendEntity;
import com.example.administrator.himalaya.entity.recommendentity.RecommendEntityIF03;
import com.example.administrator.himalaya.entity.recommendentity.RecommendEntityInterFace02;
import com.example.administrator.himalaya.entity.recommendentity.RecommendFocus;
import com.example.administrator.himalaya.testPackage.Myservice;
import com.example.administrator.himalaya.testPackage.Myservice02;
import com.example.administrator.himalaya.testPackage.MytestAdapter;
import com.example.administrator.himalaya.testPackage.PicLoad;
import com.example.administrator.himalaya.testPackage.RecommendHeader2Adapter;
import com.example.administrator.himalaya.testPackage.RecommendHeaderAdapter;
import com.example.administrator.himalaya.testPackage.RecommendIF03Service;
import com.example.administrator.himalaya.testPackage.RecommendfooterAdapter;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentDicsoverRecommend extends Fragment implements ViewPager.OnPageChangeListener, Callback<RecommendEntity> {


    private final String BASE_URL = "http://mobile.ximalaya.com/mobile/discovery/";
    private List<ImageView> listImage;
    private List<ImageView> footListImage;
    private int imageIds = R.drawable.myspin_image_default_album_s;
    private List<RecommendEntity> list;
    private List<RecommendEntityInterFace02> list2;
    private MytestAdapter adapter;
    private RecommendHeader2Adapter header2Adapter;
    private ViewPager viewPager, footViewPager, viewPagerHead02;
    private int curPosition = 1;
    private int curPosition02 = 1;
    private int prePosition=0;
    private int headImagesSize;
    private LinearLayout pointContainer;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int currentItem=viewPager.getCurrentItem();
            viewPager.setCurrentItem(++currentItem);

        }
    };
    Handler handlerfoot = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int currentItem=footViewPager.getCurrentItem();
            footViewPager.setCurrentItem(++currentItem);

        }
    };


    public FragmentDicsoverRecommend() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_one, container, false);
    }

    private void CarouselRecommend() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                        try {
                            Thread.sleep(2000);
                            handler.sendEmptyMessage(0);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }

        }).start();
    }

    private void CarouselRecommendfoot() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(2000);
                        handlerfoot.sendEmptyMessage(0);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }

        }).start();
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        list = new ArrayList<>();
        list2 = new ArrayList<>();
        adapter = new MytestAdapter(list, list2, getContext());

        RecyclerView recycle = (RecyclerView) view.findViewById(R.id.anchor_recycleView);
        recycle.setLayoutManager(new LinearLayoutManager(getContext()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

//        RecyclerViewHeader header = (RecyclerViewHeader) view.findViewById(R.id.anchor_recycleView_header);
        viewPager = (ViewPager) view.findViewById(R.id.anchor_viewpager_head);
        footViewPager = (ViewPager) view.findViewById(R.id.anchor_viewpager_foot);
        viewPagerHead02 = (ViewPager) view.findViewById(R.id.anchor_viewpager_head2);
        pointContainer =(LinearLayout) view.findViewById(R.id.pointcontainer);
        listImage = new ArrayList<>();

        footListImage = new ArrayList<>();
//        for(int i=0;i<3;i++){
//            ImageView imageView=new ImageView(getContext());
//            imageView.setImageResource(imageIds);
//            listImage.add(imageView);
//        }

//        header.attachTo(recycle);
        viewPager.addOnPageChangeListener(this);
        footViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                curPosition02 = position;
//                if(position-1<0){
//                    pointContainer.getChildAt(position-1).setSelected(true);
//                }
//                pointContainer.getChildAt(position-1).setSelected(true);
//                pointContainer.getChildAt(prePosition).setSelected(false);
//                prePosition=position-1;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_IDLE:
                        if (curPosition02 == 0) {
                            footViewPager.setCurrentItem(footListImage.size() - 2, false);
                        } else if (curPosition02 == footListImage.size() - 1) {
                            footViewPager.setCurrentItem(1, false);
                        }
                        break;
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        break;
                    case ViewPager.SCROLL_STATE_SETTLING:
                        break;
                }
            }
        });
        recycle.setAdapter(adapter);
        Myservice02 topService2 = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(Myservice02.class);
        topService2.getHotAndGuess("android").enqueue(new Callback<RecommendEntityInterFace02>() {
            @Override
            public void onResponse(Call<RecommendEntityInterFace02> call, Response<RecommendEntityInterFace02> response) {
                RecommendEntityInterFace02 recommendIFEntity = response.body();

                adapter.adddatas(null, recommendIFEntity);
            }

            @Override
            public void onFailure(Call<RecommendEntityInterFace02> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        Myservice topService = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(Myservice.class);
        topService.getEntity("and-a1", "android", true, true, 2, "4.3.98").enqueue(this);

        RecommendIF03Service if03Service = new Retrofit.Builder()
                .baseUrl("http://adse.ximalaya.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(RecommendIF03Service.class);
        if03Service.getData("android", "find_banner", "wifi", 0, "4.3.98").enqueue(new Callback<RecommendEntityIF03>() {
            @Override
            public void onResponse(Call<RecommendEntityIF03> call, Response<RecommendEntityIF03> response) {
                RecommendEntityIF03 entityIF03 = response.body();
                List<IF03DataEntity> data = entityIF03.getData();
                int dataSize = data.size();
                for (int i = 0; i <= dataSize + 1; i++) {
                    ImageView imageView;
                    if (i == 0) {
                        imageView = PicLoad.loadImage(new ImageView(getContext()), data.get(dataSize - 1).getCover());
                    } else if (i == dataSize + 1) {
                        imageView = PicLoad.loadImage(new ImageView(getContext()), data.get(0).getCover());
                    } else {
                        imageView = PicLoad.loadImage(new ImageView(getContext()), data.get(i - 1).getCover());
                    }
                    footListImage.add(imageView);

                }
                RecommendfooterAdapter footAdapter = new RecommendfooterAdapter(footListImage);
                footViewPager.setAdapter(footAdapter);
                CarouselRecommendfoot();
                footViewPager.setCurrentItem(1, false);
            }

            @Override
            public void onFailure(Call<RecommendEntityIF03> call, Throwable t) {

            }
        });
//device=android &name=find_banner &network=wifi   &operator=0   &version=4.3.98
    }

    @Override
    public void onResponse(Call<RecommendEntity> call, Response<RecommendEntity> response) {
        RecommendEntity recommendEntity = response.body();
        adapter.adddatas(recommendEntity, null);
        RecommendFocus imagedata = recommendEntity.getFocusImages();
        List<DiscoveryListEntity> discoveryImageList = recommendEntity.getDiscoveryColumns().getList();
        header2Adapter = new RecommendHeader2Adapter(discoveryImageList, getContext());
        viewPagerHead02.setAdapter(header2Adapter);
        List<FocusList> iamgelist = imagedata.getList();
        headImagesSize = iamgelist.size();
        for (int i = 0; i <= headImagesSize + 1; i++) {
            ImageView imageView;
            DisplayMetrics dm = new DisplayMetrics();
            //获取屏幕信息
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenWidth = dm.widthPixels;
            int screenHeigh = dm.heightPixels;
            if (i == 0) {
                imageView = PicLoad.loadImage(new ImageView(getContext()), iamgelist.get(headImagesSize - 1).getPic());
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//                    ViewGroup.LayoutParams params = imageView.getLayoutParams();
//                    int oldWidth=imageView.getWidth();
//                    params.width=screenWidth;
//                    params.height=imageView.getHeight()*(screenWidth/oldWidth);
//                    imageView.setLayoutParams(params);
            } else if (i == headImagesSize + 1) {
                imageView = PicLoad.loadImage(new ImageView(getContext()), iamgelist.get(0).getPic());
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//  ViewGroup.LayoutParams params = imageView.getLayoutParams();
//                    int oldWidth=imageView.getWidth();
//                    params.width=screenWidth;
//                    params.height=imageView.getHeight()*(screenWidth/oldWidth);
            } else {
                imageView = PicLoad.loadImage(new ImageView(getContext()), iamgelist.get(i - 1).getPic());
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//   ViewGroup.LayoutParams params = imageView.getLayoutParams();
//                    int oldWidth=imageView.getWidth();
//                    params.width=screenWidth;
//                    params.height=imageView.getHeight()*(screenWidth/oldWidth);
            }
            listImage.add(imageView);
        }
        RecommendHeaderAdapter headerAdapter = new RecommendHeaderAdapter(listImage);
        viewPager.setAdapter(headerAdapter);
        for(int i=0;i<listImage.size();i++){
            ImageView imageView = new ImageView(getContext());
            imageView.setImageResource(R.drawable.point_selector);
            LinearLayout.LayoutParams params =new LinearLayout.LayoutParams(
                   20,
                   20);
            if(i != 0) {
                params.leftMargin = 8;
                imageView.setSelected(false);//设置除第一个圆点外的圆点都为黑色
            }
            imageView.setLayoutParams(params);
            pointContainer.addView(imageView);
        }

        viewPager.setCurrentItem(1, false);
        CarouselRecommend();
//         else if ((RecommendEntityInterFace02)father instanceof RecommendEntityInterFace02) {
//            RecommendEntityInterFace02 RecommendIFEntity = (RecommendEntityInterFace02)father;
//            Log.d("123", "onResponse: "+RecommendIFEntity.toString());
//            adapter.adddatas(null, RecommendIFEntity);

    }

    @Override
    public void onFailure(Call<RecommendEntity> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
    }

    //header图片加载
    public void header() {

    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        curPosition = position;
//        if(position==0) {
//            pointContainer.getChildAt(listImage.size()-1).setEnabled(true);
//            pointContainer.getChildAt(prePosition).setEnabled(false);
//            prePosition=listImage.size()-1;
//        }
//        else if(position==(listImage.size()+1)){
//            pointContainer.getChildAt(0).setEnabled(true);
//            pointContainer.getChildAt(prePosition).setEnabled(false);
//            prePosition=0;
//
//        }
//        else{
//            pointContainer.getChildAt(position - 1).setEnabled(true);
//            pointContainer.getChildAt(prePosition).setSelected(false);
//            prePosition=position - 1;
//        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
            case ViewPager.SCROLL_STATE_IDLE:
                if (curPosition == 0) {
                    viewPager.setCurrentItem(listImage.size() - 2, false);
                } else if (curPosition == listImage.size() - 1) {
                    viewPager.setCurrentItem(1, false);
                }
                break;
            case ViewPager.SCROLL_STATE_DRAGGING:
                break;
            case ViewPager.SCROLL_STATE_SETTLING:
                break;
        }
    }

}
